package com.zufangbao.earth.web.controller.particalsystem;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.demo2do.core.web.resolver.Secure;
import com.zufangbao.earth.PageView;
import com.zufangbao.earth.RoleSpec;
import com.zufangbao.earth.entity.particalsystem.AppParticles;
import com.zufangbao.earth.entity.particalsystem.Partical;
import com.zufangbao.earth.entity.security.Principal;
import com.zufangbao.earth.handler.BillDepositeHandler;
import com.zufangbao.earth.service.AppParticlesService;
import com.zufangbao.earth.service.ParticalService;
import com.zufangbao.gluon.api.quark.AppConfig;
import com.zufangbao.gluon.api.quark.ApiSpecAppConfig.AppConfigDbFields;
import com.zufangbao.gluon.exception.CommonException;
import com.zufangbao.gluon.handler.BaseViewSpecHandler;
import com.zufangbao.gluon.handler.ResultHandler;
import com.zufangbao.gluon.spec.earth.GlobalSpec4Earth;
import com.zufangbao.gluon.spec.global.GlobalCodeSpec;
import com.zufangbao.gluon.spec.global.GlobalMsgSpec;
import com.zufangbao.gluon.spec.global.GlobalCodeSpec.GeneralErrorCode;
import com.zufangbao.sun.entity.Channel;
import com.zufangbao.sun.entity.company.corp.App;
import com.zufangbao.sun.entity.company.corp.AppAccount;
import com.zufangbao.sun.entity.company.corp.AppServiceConfig;
import com.zufangbao.sun.service.AppService;

@Controller
@RequestMapping("/particalsystem")
public class AppParticlesController {
	
	public static Log logger = LogFactory.getLog(ParticalController.class);
	
	@Qualifier("viewSpecHandler")
	@Autowired
	private BaseViewSpecHandler redirectSpecHandler;
	
	@Autowired
	private ResultHandler resultHandler;
	
	@Autowired
	private ParticalService particalService;
	
	@Autowired
	private AppParticlesService appParticlesService;
	
	@Autowired
	private AppService appService;
	
	@Autowired
	private BillDepositeHandler billDepositeHandler;
	
	
	public ModelAndView loadAppParticles(@Secure Principal principal) {
		
		if(! principal.getAuthority().equals(RoleSpec.ROLE_SUPER_USER)){
			
			return redirectSpecHandler.noAuthorityPageSpec();
		}
		ModelAndView modelAndView = new ModelAndView(PageView.PAGE_LOAD_APP_PARTICLES);
		
		List<Partical> particalList = particalService.loadAllQuarks();
		
		List<AppParticles> appParticlesList = appParticlesService.loadAll(AppParticles.class);
		
		modelAndView.addObject("particals", particalList);
		
		modelAndView.addObject("appParticles", appParticlesList);
		
		return modelAndView;
	}
	
	@RequestMapping("/create-app-particles")
	public @ResponseBody String createAppParticles(@Secure Principal principal,
			AppParticles appParticle) {
		
		if(! principal.getAuthority().equals(RoleSpec.ROLE_SUPER_USER)){
			
			return resultHandler.errorJsonResult(GeneralErrorCode.ERROR_NO_AUTHORITY, com.zufangbao.gluon.spec.global.GlobalMsgSpec.GeneralErrorMsg.MSG_NO_AUTHORITY);
			
		}
		if(isNotValidAppParticles(appParticle)){
			
			return resultHandler.errorJsonResult(GlobalSpec4Earth.ERROR_ILLEGAL_PARAMS,com.zufangbao.gluon.spec.global.GlobalMsgSpec.GeneralErrorMsg.MSG_ILLEGAL_REQ);
			
		}
		try {
			
			appParticlesService.saveAppParticle(appParticle);
			
			return resultHandler.sucJsonResult();
			
		} catch (CommonException e) {
			
			return resultHandler.errorJsonResult(e.getErrorCode(),e.getErrorMsg());
		}
	}
	
	private boolean isNotValidAppParticles(AppParticles appParticle) {
		
		return appParticle == null || StringUtils.isEmpty(appParticle.getAppId()) || StringUtils.isEmpty(appParticle.getUniqueParticalId());
	}
	
	@RequestMapping(value = "/delete-app-particles",method = RequestMethod.POST)
	public @ResponseBody String deleteAppParticles(@Secure Principal principal, @RequestParam("appParticleId")Long appParticleId) {
		
		if(! principal.getAuthority().equals(RoleSpec.ROLE_SUPER_USER)){
			
			return resultHandler.errorJsonResult(GeneralErrorCode.ERROR_NO_AUTHORITY, com.zufangbao.gluon.spec.global.GlobalMsgSpec.GeneralErrorMsg.MSG_NO_AUTHORITY);
			
		}
		if(isNotValidAppParticalId(appParticleId)){
			
			return resultHandler.errorJsonResult(GlobalSpec4Earth.ERROR_ILLEGAL_PARAMS,com.zufangbao.gluon.spec.global.GlobalMsgSpec.GeneralErrorMsg.MSG_ILLEGAL_REQ);
			
		}
		appParticlesService.deleteAppParticle(appParticleId);
		
		return resultHandler.sucJsonResult();
	}

	private boolean isNotValidAppParticalId(Long appParticleId) {
		
		return StringUtils.isEmpty(appParticleId) || appParticlesService.load(AppParticles.class, appParticleId) == null;
	}

	@RequestMapping(value = "/sync-app-config",method = RequestMethod.POST)
	public @ResponseBody String syncAppConfig(@Secure Principal principal, @RequestParam("particalUniqueId")String particalUniqueId,
			@RequestParam("appId")String appId) {
		
		if(! principal.getAuthority().equals(RoleSpec.ROLE_SUPER_USER)){
			
			return resultHandler.errorJsonResult(GeneralErrorCode.ERROR_NO_AUTHORITY, com.zufangbao.gluon.spec.global.GlobalMsgSpec.GeneralErrorMsg.MSG_NO_AUTHORITY);
			
		}
		if(isNotValidAppId(appId) || isNotValidPaticalUniqueId(particalUniqueId)){
			
			return resultHandler.errorJsonResult(GlobalSpec4Earth.ERROR_ILLEGAL_PARAMS,com.zufangbao.gluon.spec.global.GlobalMsgSpec.GeneralErrorMsg.MSG_ILLEGAL_REQ);
			
		}
		App app = appService.getApp(appId);
		
		List<AppConfig> appConfigList = new ArrayList<AppConfig>();
		
		List<AppServiceConfig> appServiceConfigList = appService.getAppServiceConfig(app, Channel.MOBILE);
		
		AppAccount appAccount = appService.getAppAccount(app, Channel.MOBILE);
		
		AppConfig appConfig = null;
		
		List<String> syncAppConfigNameList = new ArrayList<String>();
		
		syncAppConfigNameList.add(AppConfigDbFields.APP_CONFIG_KEY_APP_SECRET);
		syncAppConfigNameList.add(AppConfigDbFields.APP_CONFIG_KEY_RETURN_URL);
		syncAppConfigNameList.add(AppConfigDbFields.APP_CONFIG_KEY_NOTIFY_URL);
		syncAppConfigNameList.add(AppConfigDbFields.APP_CONFIG_KEY_LOGO_URL);
		syncAppConfigNameList.add(AppConfigDbFields.APP_CONFIG_KEY_APP_BILL_PAGE_URL);
		syncAppConfigNameList.add(AppConfigDbFields.APP_CONFIG_KEY_APP_CONSULT_PAGE_URL);
		
		for(AppServiceConfig item : appServiceConfigList){
			
			if(syncAppConfigNameList.contains(item.getName())){
				
				appConfig = new AppConfig(appId, item.getName(), item.getUrl());
				appConfigList.add(appConfig);
				
			}
			
		}
		appConfig = new AppConfig(appId, AppConfigDbFields.APP_CONFIG_KEY_APP_SECRET, app.getAppSecret());
		appConfigList.add(appConfig);
		appConfig = new AppConfig(appId, AppConfigDbFields.APP_CONFIG_KEY_LOGO_URL, appAccount.getLogo());
		appConfigList.add(appConfig);
		
		try {
			boolean isSyncAppConfigSuc = billDepositeHandler.syncAppConfig(particalUniqueId, appConfigList);
			
			if(!isSyncAppConfigSuc){
				
				return resultHandler.errorJsonResult(GlobalCodeSpec.CODE_FAILURE, GlobalMsgSpec.GeneralErrorMsg.MSG_SYSTEM_ERROR);
			}
			
			return resultHandler.sucJsonResult();
			
		} catch (CommonException e) {
			
			return resultHandler.errorJsonResult(e.getErrorCode(),e.getErrorMsg());
		}
		
	}
	private boolean isNotValidAppId(String appId){
		
		return StringUtils.isEmpty(appId) || appService.getApp(appId) == null || appService.getApp(appId).isDisabled();
	}
	private boolean isNotValidPaticalUniqueId(String particalUniqueId){
		
		return StringUtils.isEmpty(particalUniqueId) || particalService.getParticalByUniqueId(particalUniqueId) == null;
		
	}
}
